package net.zjitc.exception;

import lombok.extern.slf4j.Slf4j;
import net.zjitc.common.ResponseResult;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

/**
 * @author 毛钰深
 * @create 2022/1/23
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
//全局异常处理器,捕获的仅是Controller里面产生的所有异常,然后处理
public class GlobalExceptionHandler {

    private ResponseResult res;

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    public ResponseResult handler(AccessDeniedException e){
        log.error("security权限不足：----------------{}", e.getMessage());
        res=new ResponseResult<>();
        res.setForbidden("权限不足");
        return res;
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handler(MethodArgumentNotValidException e) {
        log.error("实体校验异常：----------------{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        res=new ResponseResult<>();
        res.setBadRequest(objectError.getDefaultMessage());
        return res;
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseResult handler(IllegalArgumentException e) {
        log.error("Assert异常：----------------{}", e.getMessage());
        res=new ResponseResult<>();
        res.setBadRequest(e.getMessage());
        return res;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseResult handler(RuntimeException e) {
        log.error("运行时异常：----------------{}", e.getMessage());
        res=new ResponseResult<>();
        res.setError(e.getMessage());
        return res;
    }

}
